package wsepForum.ui.console;

import java.util.HashSet;
import wsepForum.common.elements.*;
import wsepForum.domain.Session;

public class ConsoleUIParser {
	private ConsoleUIReplyGenerator replyGen;

	public ConsoleUIParser() {
		this.replyGen = new ConsoleUIReplyGenerator();
	}

	public String parseMessage(String message,Session session) {

		//minimizing all spaces for easy parsing.
		String trimmedMsg = message.trim().replaceAll(" +", " ");
		String reply="";
		//separating command and parameters (if any).
		String command;
		String parameters;
		if (trimmedMsg.indexOf(' ')!=-1) {
			command = trimmedMsg.substring(0, trimmedMsg.indexOf(' '));
			parameters = trimmedMsg.substring(trimmedMsg.indexOf(' ')+1, trimmedMsg.length());
		}
		else {
			command = trimmedMsg;
			parameters = "";
		}

		//determining what command has been used
		if (command.equals("ls")) {
			reply = this.parseLS(parameters.split(" "),session);
		} else {
		if (command.equals("cdt")) {
			reply = this.parseCDT(parameters.split(" "),session);
		} else {
		if (command.equals("cds")) {
			reply = this.parseCDS(parameters.split(" "),session);
		} else
		if (command.equals("login")) {
			reply = this.parseLogin(parameters.split(" "),session);
		} else {
		if (command.equals("logout")) {
			reply = this.parseLogout(parameters.split(" "),session);
		} else {
		if (command.equals("register")) {
			reply = this.parseRegister(parameters.split(" "),session);
		} else {
		if (command.equals("addsec")) {
			reply = this.parseAddsec(parameters.split(" "),session);
		} else {
		if (command.equals("addtop")) {
			reply = this.parseAddtop(parameters.split(" >"),session);
		} else {
		if (command.equals("addmes")) {
			reply = this.parseAddmes(parameters.split(" >"),session);
		} else {
		if (command.equals("edit")) {
			reply = this.parseEdit(parameters.split(" >"),session);
		} else {
		if (command.equals("delmes")) {
			reply = this.parseDelmes(parameters.split(" "),session);
		} else {
		if (command.equals("delsec")) {
			reply = this.parseDelsec(parameters.split(" "),session);
		} else {
		if (command.equals("addmod")) {
			reply = this.parseAddmod(parameters.split(" "),session);
		} else {
		if (command.equals("delmod")) {
			reply = this.parseDelmod(parameters.split(" "),session);
		} else {
		if (command.equals("deluser")) {
			reply = this.parseDeluser(parameters.split(" "),session);
		} else {
		if 	(command.equals("cd..")) {
			reply = this.parseCD(parameters.split(" "),session);
		} else {
		if 	(command.equals("help")) {
			reply = this.parseHelp(parameters.split(" "),session);
		} else {
			reply = "No such command. Try \"help\".";
		}}}}}}}}}}}}}}}}
		return reply;
	}

	private String parseLS(String[] params, Session session) {
		if ((params.length>1) || (!params[0].equals(""))) {
			return "[FAIL: no parameters are allowed for this command]\n\r";
		}
		else {
			return this.replyGen.lsReplyGen(session);
		}
	}

	private String parseCDT(String[] params, Session session) {
		if ((params.length>1) || (params[0].equals("")))
			return "[FAIL: wrong number of parmeters]\n\r";
		else {
			try {
				int topicNum = Integer.parseInt(params[0]);
				return this.replyGen.cdtReplyGen(topicNum,session);
			} catch (NumberFormatException e) {
				return "[FAIL: parameter is not a number]\n\r";
			}
		}
	}
	private String parseCDS(String[] params, Session session) {
		if ((params.length>1) || (params[0].equals("")))
			return "[FAIL: wrong number of parmeters]\n\r";
		else {
			try {
				int sectionNum = Integer.parseInt(params[0]);
				return this.replyGen.cdsReplyGen(sectionNum,session);
			} catch (NumberFormatException e) {
				return "[FAIL: Parameter is not a number]\n\r";
			}
		}
	}

	private String parseLogin(String[] params, Session session) {
		if (params.length!=2) {
			return "[FAIL: Wrong number of parameters]\n\r";
		}
		else {
			try {
				if (session.login(params[0], params[1])) {
					return "Login Success! Welcome "+params[0]+"\n\r";
				}
				else {
					return "[FAIL: User-name or password are incorrect or you are already logged-in]\n\r";
				}
			} catch (Exception e) {
				return "[FAIL: User-name or password are incorrect or you are already logged-in]\n\r";
			}
		}
	}

	private String parseLogout(String[] params, Session session) {
		if ((params.length>1) || (!params[0].equals(""))) {
			return "[FAIL: no parameters are allowed for this command]\n\r";
		}
		else {
			if (session.logout()) {
				return "Logout Success! Goodbye, please visit again soon!\n\r";
			}
			else {
				return "[FAIL: could not logout. either not logged-in or error accurred]\n\r";
			}
		}
	}

	private String parseRegister(String[] params, Session session) {
		if (params.length!=2) {
			return "[FAIL: Wrong number of parameters]\n\r";
		}
		else {
			try {
				if (session.getHandler().register(params[0], params[1])) {
					return "Registration Succeded! Please login\n\r";
				}
				else {
					return "[FAIL: UserName already exists or illegal, or password illegal]";
				}
			} catch (Exception e) {
				return "[FAIL: You are un-authorized to perform this action]\n\r";
			}
		}
	}

	private String parseAddsec(String[] params, Session session) {
		if ((params.length>1) || (params[0].equals(""))) {
			return "[FAIL: Wrong number of parameters]\n\r";
		}
		else {
			if (!session.getUiState().isSection()) {
				return "[FAIL: Cannot create sections in topics]\n\r";
			}
			else {
				try {
					session.getHandler().createSection(session.getUiState().getCurrentElementID(), params[0], new HashSet<String>());
					return "Section created successfuly!\n\r";
				} catch (Exception e) {
					return "[FAIL: You are unauthorized to perform this action]\n\r";
				}
			}
		}
	}

	private String parseAddtop(String[] params, Session session) {
		if (params.length!=2) {
			return "[FAIL: The correct format is: addtop >headline >body  ]\n\r";
		}
		else {
			if (!session.getUiState().isSection()) {
				return "[FAIL: Cannot create topics inside a topic]\n\r";
			}
			else {
				try {
					session.getHandler().createTopic(session.getUiState().getCurrentElementID(), params[0].substring(1), params[1]);
					return "Topic created successfuly!\n\r";
				} catch (Exception e) {
					return "[FAIL: You are unauthorized to perform this action]\n\r";
				}
			}
		}
	}

	private String parseAddmes(String[] params, Session session) {
		if (params.length!=2) {
			return "[FAIL: The correct format is: addtop >headline >body  ]\n\r";
		}
		else {
			if (session.getUiState().isSection()) {
				return "[FAIL: Cannot add messages inside a section]\n\r";
			}
			else {
				try {
					session.getHandler().addMessageToTopic(session.getUiState().getCurrentElementID(), params[0].substring(1), params[1]);
					return "Message created successfuly!\n\r";
				} catch (Exception e) {
					return "[FAIL: You are unauthorized to perform this action]\n\r";
				}
			}
		}
	}


	private String parseEdit(String[] params, Session session) {
		if (params.length!=3) {
			return "[FAIL: The correct format is: edit >message-number >headline >body  ]\n\r";
		}
		else {
			if (session.getUiState().isSection()) {
				return "[FAIL: Cannot edit messages inside a section]\n\r";
			}
			else {
				try {
					int messageNum = Integer.parseInt(params[0].substring(1));
					Topic currentTopic = session.getHandler().getTopic(session.getUiState().getCurrentElementID());
					if ((messageNum<1) || (messageNum>currentTopic.getAllMessages().size())) {
						return "[FAIL: No such message exists in this topic]\n\r";
					}
					else {
						Message mess = currentTopic.getAllMessages().elementAt(messageNum-1);
						session.getHandler().editMessage(session.getUiState().getCurrentElementID(),mess.getElementID(), params[1], params[2]);
						return "Message editted successfuly!";
					}
				} catch (NumberFormatException e) {
					return "[FAIL: The correct format is: edit >message-number >headline >body  ]\n\r";
				} catch (Exception e) {
					return "[FAIL: You are unauthorized to perform this action]\n\r";
				}
			}
		}
	}

	private String parseDelmes(String[] params, Session session) {
		if ((params.length!=1) || (params[0].equals(""))) {
			return "[FAIL: The correct format is: delmes message-number]\n\r";
		}
		else {
			if (session.getUiState().isSection()) {
				return "[FAIL: Cannot edit messages inside a section]\n\r";
			}
			else {
				try {
					int messageNum = Integer.parseInt(params[0]);
					Topic currentTopic = session.getHandler().getTopic(session.getUiState().getCurrentElementID());
					if ((messageNum<1) || (messageNum>currentTopic.getAllMessages().size())) {
						return "[FAIL: No such message exists in this topic]\n\r";
					}
					else {
						Message mess = currentTopic.getAllMessages().elementAt(messageNum-1);
						session.getHandler().deleteMessage(session.getUiState().getCurrentElementID(), mess.getElementID());
						return "Message deleted successfuly!";
					}
				} catch (NumberFormatException e) {
					return "[FAIL: The correct format is: delmes message-number]\n\r";
				} catch (Exception e) {
					return "[FAIL: You are unauthorized to perform this action]\n\r";
				}
			}
		}
	}

	private String parseDelsec(String[] params, Session session) {
		if ((params.length!=1) || (params[0].equals(""))) {
			return "[FAIL: The correct format is: delsec section-number]\n\r";
		}
		else {
			if (!session.getUiState().isSection()) {
				return "[FAIL: There are no sections inside a topic]\n\r";
			}
			else {
				try {
					int sectionNum = Integer.parseInt(params[0]);
					Section currentSection = session.getHandler().getSection(session.getUiState().getCurrentElementID());
					if ((sectionNum<1) || (sectionNum>currentSection.getAllSectionHeaders().size())) {
						return "[FAIL: No such sub-section exists in this section]\n\r";
					}
					else {
						session.getHandler().removeSection(currentSection.getAllSectionHeaders().elementAt(sectionNum-1).getElementID());
						return "Section deleted successfuly!";
					}
				} catch (NumberFormatException e) {
					return "[FAIL: The correct format is: delsec section-number]\n\r";
				} catch (Exception e) {
					return "[FAIL: You are unauthorized to perform this action]\n\r";
				}
			}
		}
	}

	private String parseAddmod(String[] params, Session session) {
		if ((params.length!=1) || (params[0].equals(""))) {
			return "[FAIL: The correct format is: addmod username]\n\r";
		}
		else {
			if (!session.getUiState().isSection()) {
				return "[FAIL: You are currently not directly in a section]\n\r";
			}
			else {
				try {
					session.getHandler().addModeratorToSection(session.getUiState().getCurrentElementID(), params[0]);
					return "Moderator was added to current section!\n\r";
				} catch (Exception e) {
					return "[FAIL: UserName is not a moderator, or you are not authorized]\n\r";
				}
			}
		}
	}

	private String parseDelmod(String[] params, Session session) {
		if ((params.length!=1) || (params[0].equals(""))) {
			return "[FAIL: The correct format is: delmod username]\n\r";
		}
		else {
			if (!session.getUiState().isSection()) {
				return "[FAIL: You are currently not directly in a section]\n\r";
			}
			else {
				try {
					session.getHandler().removeModerator(session.getUiState().getCurrentElementID(), params[0]);
					return "Moderator was deleted from section!\n\r";
				} catch (Exception e) {
					return "[FAIL: UserName is not a moderator, or you are not authorized]\n\r";
				}
			}
		}
	}

	private String parseDeluser(String[] params, Session session) {
		if ((params.length!=1) || (params[0].equals(""))) {
			return "[FAIL: The correct format is: delmod username]\n\r";
		}
		else {
			try {
				session.getHandler().removeUser(params[0]);
				return "User was deleted successfuly\n\r";
			} catch (Exception e) {
				return "[FAIL: UserName is not a moderator, or you are not authorized]\n\r";
			}
		}
	}

	private String parseCD(String[] params, Session session) {
		if ((params.length!=1) || (!params[0].equals(""))) {
			return "[FAIL: No parameters are allowed]\n\r";
		}
		else {
			try {
				if (session.getUiState().getCurrentElementID()!=0) {
					if (session.getUiState().isSection()) {
						session.getUiState().setCurrentElementID(session.getHandler().getSection(session.getUiState().getCurrentElementID()).getParentID());
					}
					else {
						session.getUiState().setCurrentElementID(session.getHandler().getTopic(session.getUiState().getCurrentElementID()).getParentID());
					}
					session.getUiState().setIsSection(true);
					String path = session.getUiState().getPath();
					session.getUiState().setPath(path.substring(0, path.lastIndexOf('\\')));
				}
				return "Current user location: "+session.getUiState().getPath();
			} catch (Exception e) {
				return "[FAIL: Data-base error]\n\r";
			}
		}
	}

	private String parseHelp(String[] params, Session session) {
		if ((params.length!=1) || (!params[0].equals(""))) {
			return "[FAIL: No parameters are allowed]\n\r";
		}
		else {
			return this.replyGen.helpReplyGen();
		}
	}
}
